import axios from 'axios';
import { ProcessingOptions, ImageProcessingResult } from '../types';

const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8000';

const apiClient = axios.create({
  baseURL: API_BASE_URL,
  timeout: 30000,
});

export class ImageService {
  static async uploadImage(file: File): Promise<string> {
    const formData = new FormData();
    formData.append('file', file);

    const response = await apiClient.post('/api/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });

    return response.data.url;
  }

  static async processImage(
    imageData: string,
    options: ProcessingOptions
  ): Promise<ImageProcessingResult> {
    try {
      const response = await apiClient.post('/api/process', {
        image: imageData,
        type: options.type,
        parameters: options.parameters,
      });

      return {
        success: true,
        data: response.data.result,
      };
    } catch (error: any) {
      return {
        success: false,
        error: error.response?.data?.message || error.message,
      };
    }
  }

  static async enhanceImage(imageData: string): Promise<ImageProcessingResult> {
    return this.processImage(imageData, { type: 'enhance' });
  }

  static async removeBackground(imageData: string): Promise<ImageProcessingResult> {
    return this.processImage(imageData, { type: 'background-remove' });
  }

  static async upscaleImage(
    imageData: string,
    scale: number = 2
  ): Promise<ImageProcessingResult> {
    return this.processImage(imageData, {
      type: 'upscale',
      parameters: { scale },
    });
  }

  static async denoiseImage(imageData: string): Promise<ImageProcessingResult> {
    return this.processImage(imageData, { type: 'denoise' });
  }

  // 本地图像处理方法
  static applyFilters(
    canvas: HTMLCanvasElement,
    filters: {
      brightness: number;
      contrast: number;
      saturation: number;
      blur: number;
    }
  ): void {
    const ctx = canvas.getContext('2d');
    if (!ctx) return;

    const filterString = [
      `brightness(${100 + filters.brightness}%)`,
      `contrast(${100 + filters.contrast}%)`,
      `saturate(${100 + filters.saturation}%)`,
      `blur(${filters.blur}px)`,
    ].join(' ');

    ctx.filter = filterString;
  }

  static canvasToBlob(canvas: HTMLCanvasElement): Promise<Blob> {
    return new Promise((resolve) => {
      canvas.toBlob((blob) => {
        resolve(blob!);
      }, 'image/png');
    });
  }

  static blobToBase64(blob: Blob): Promise<string> {
    return new Promise((resolve) => {
      const reader = new FileReader();
      reader.onload = () => resolve(reader.result as string);
      reader.readAsDataURL(blob);
    });
  }
}